# -*- coding: utf-8 -*-
import datetime
import math
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urljoin, json, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class JiangsuNanjingGxjPolicy(BaseTaxPolicySpider):
    name = 'jiangsu_xuzhou_policy'

    province = '江苏省'
    city = '徐州市'
    # county = ''
    park = ''

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 500, 200, 202, 502, 429, 521],
                # "DOWNLOAD_DELAY": 5,

                'DEFAULT_REQUEST_HEADERS': {
                    'Accept': 'application/json, text/javascript, */*; q=0.01',
                    'Accept-Language': 'zh,en;q=0.9,zh-CN;q=0.8',
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                "DOWNLOADER_MIDDLEWARES": {
                    "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                    **downloader_middlewares
                }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['徐州市人民政府', "", "https://www.xz.gov.cn/dynamic/zwgk/govInfoPubright.html?categorynum=003001004"],
            ['徐州市人民政府', "", "https://www.xz.gov.cn/dynamic/zwgk/govInfoPubright.html?categorynum=003001002"],

        ]:
            item = {'source': source, 'county': county}
            categorynum = url.split("categorynum=")[-1]
            yield scrapy.Request(url, callback=self.parse_content, meta={'item': item, 'categorynum': categorynum}, dont_filter=True)

    def parse_content(self, response, **kwargs):
        meta = response.meta
        gov_listTwoPage = response.xpath("//script").re_first(r'="(.*Common\.js)"')
        yield response.follow(gov_listTwoPage, callback=self.parse_js1, meta=meta, dont_filter=True)

    def parse_js1(self, response, **kwargs):
        meta = response.meta
        projectName = response.xpath(""".""").re_first(r'projectName"\s*:\s*"(.*?)"')
        meta['projectName'] = projectName
        yield response.follow('/js/ajaxReq.js', callback=self.parse_js2, meta=meta, dont_filter=True)

    def parse_js2(self, response, **kwargs):
        meta = response.meta
        siteGuid = response.xpath(""".""").re_first(r'siteGuid"?\s*[=:]+\s*"(.*?)"')
        # deptcode = response.xpath(""".""").re_first(r'deptcode\s*=\s*"(.*?)"')
        # catenum = response.xpath(""".""").re_first(r'catenum\s*=\s*"(.*?)"')
        category_api = response.xpath(""".""").re_first(r'projectName\s*\+\s*"(.*?getgovinfolist.*?)"')
        projectName = response.meta['projectName']
        data = {
            "deptcode": "",
            "siteGuid": siteGuid,
            "pageIndex": "0",
            "pageSize": "100",
            "categorynum": meta['categorynum']
        }
        meta['data'] = data
        meta['projectName'] = projectName
        # data = json.dumps(data, separators=(',', ':'))
        # print(data)
        url = response.urljoin(projectName + category_api)
        yield scrapy.Request(url, body=json.dumps(data), callback=self.parse_list, meta=meta,
                             method="POST", dont_filter=True)

    def parse_list(self, response, **kwargs):
        # print(response.request)
        prev_item = response.meta.get('item')
        datas = response.json()['custom']
        elem_list = datas['data']
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem['infourl']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['infodate']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if 'xlsx' in item['source_url'] or 'doc' in item['source_url'] or 'pdf' in item['source_url']:
                continue
            print(response.url, elem['infourl'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            data = response.meta['data']
            pages = math.ceil(int(datas['total']) / 100)
            print(response.url, f"page: {pages}")
            for page_num in range(1, int(pages) + 1):
                data['pageIndex'] = str(page_num)
                # temp_data = json.dumps(data, separators=(',', ':'))
                yield scrapy.Request(response.url, body=json.dumps(data), callback=self.parse_list,
                                     meta={'item': prev_item, 'is_next': False},  method="POST", dont_filter=True)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl jiangsu_xuzhou_policy -a get_next=0".split())
